package com.sprouting.ops.service;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sprouting.ops.dao.*;
import com.sprouting.ops.interfaces.ConstantBase;
import com.sprouting.ops.model.*;
import com.sprouting.ops.model.qo.EnvAccountQo;
import com.sprouting.ops.model.qo.OpsEnvAccountQo;
import com.sprouting.ops.model.vo.EnvAccountVo;
import com.sprouting.ops.model.vo.OpsEnvAccountVo;
import com.sprouting.ops.utils.EntityTool;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 环境账号访问信息(OpsEnvAccount)(OPS_ENV_ACCOUNT) 表服务实现类
 *
 * @author ：lx（长沙麓谷）
 * @date 创建时间：2025-09-08 16:07:37
 */
@Service
@Slf4j
public class OpsEnvAccountService extends ServiceImpl<OpsEnvAccountDao, OpsEnvAccount> {

    @Resource
    private OpsEnvAccountDao opsEnvAccountDao;
    @Resource
    private OpsDeployDao opsDeployDao;
    @Resource
    private OpsToolDao opsToolDao;
    @Resource
    private OpsEnvDao opsEnvDao;
    @Resource
    private OpsSiteDao opsSiteDao;
    @Resource
    private OpsComponentDao opsComponentDao;
    @Resource
    private OpsAppDao opsAppDao;


    /**
     * 分页查询 环境账号访问信息
     * @param page 分页参数
     * @param query 查询参数
     * @return
     */
    public Page<OpsEnvAccountVo> getListPage(Page page, OpsEnvAccountQo query){
        Page<OpsEnvAccountVo> listPage = opsEnvAccountDao.getListPage(page, query);
        List<OpsEnvAccountVo> records = listPage.getRecords();
        if (CollUtil.isEmpty(records)){
            return listPage;
        }

        List<String> envIdList = records.stream().filter(obj -> ConstantBase.EnvAccountBindType.ENV.equals(obj.getBindType())).map(OpsEnvAccountVo::getBindId).collect(Collectors.toList());
        List<String> siteIdList = records.stream().filter(obj -> ConstantBase.EnvAccountBindType.SITE.equals(obj.getBindType())).map(OpsEnvAccountVo::getBindId).collect(Collectors.toList());
        List<String> componentIdList = records.stream().filter(obj -> ConstantBase.EnvAccountBindType.COMPONENT.equals(obj.getBindType())).map(OpsEnvAccountVo::getBindId).collect(Collectors.toList());
        List<String> toolIdList = records.stream().filter(obj -> ConstantBase.EnvAccountBindType.TOOL.equals(obj.getBindType())).map(OpsEnvAccountVo::getBindId).collect(Collectors.toList());
        List<String> appIdList = records.stream().filter(obj -> ConstantBase.EnvAccountBindType.APP.equals(obj.getBindType())).map(OpsEnvAccountVo::getBindId).collect(Collectors.toList());

        // 绑定ID -> 绑定名称
        Map<String, String> map = new HashMap<>();

        /*
        代替写法
               if (CollUtil.isNotEmpty(envIdList)){
                    List<OpsEnv> opsEnvList = opsEnvDao.selectByIds(envIdList);
                    if (CollUtil.isNotEmpty(opsEnvList)){
                        Map<String, String> envMap = opsEnvList.stream().collect(Collectors.toMap(OpsEnv::getId, OpsEnv::getName, (o, n) -> n));
                        map.putAll(envMap);
                    }
                }
         */
        addToMap(map, envIdList, ids -> opsEnvDao.selectByIds(ids), OpsEnv::getId, OpsEnv::getName);
        addToMap(map, siteIdList, ids -> opsSiteDao.selectByIds(ids), OpsSite::getId, OpsSite::getName);
        addToMap(map, componentIdList, ids -> opsComponentDao.selectByIds(ids), OpsComponent::getId, OpsComponent::getName);
        addToMap(map, toolIdList, ids -> opsToolDao.selectByIds(ids), OpsTool::getId, OpsTool::getName);
        addToMap(map, appIdList, ids -> opsAppDao.selectByIds(ids), OpsApp::getId, OpsApp::getName);

        for (OpsEnvAccountVo vo : records) {
            vo.setBindName(map.get(vo.getBindId()));
        }

        return listPage;
    }

    /**
     * 根据场所和类型查询  应用、组件、工具
     * @param siteId 场所
     * @param type 查询的类型 1 应用  2 组件  3 工具
     * @return
     */
    public List<EnvAccountVo> getEnvAccount(String siteId, Integer type) {
        if (1 == type){
            return opsDeployDao.getEnvAccountApp(siteId);

        } else if (2 == type){
            return opsDeployDao.getEnvAccountComponent(siteId);

        } else if (3 == type){
            return opsToolDao.getEnvAccountTool(siteId);
        }

        return null;
    }


    /**
     * 实体列表转换为ID-Name的映射关系
     * @param map 目标映射表，用于存储ID和名称的对应关系
     * @param idList ID列表，需要查询的实体ID集合
     * @param dataFetcher 数据获取函数，根据ID列表查询实体列表
     * @param idExtractor ID提取函数，从实体中提取ID字段
     * @param nameExtractor 名称提取函数，从实体中提取名称字段
     * @param <T> 实体类型
     */
    private <T> void addToMap(Map<String, String> map, List<String> idList, Function<List<String>, List<T>> dataFetcher, Function<T, String> idExtractor, Function<T, String> nameExtractor) {
        if (CollUtil.isNotEmpty(idList)) {
            List<T> dataList = dataFetcher.apply(idList);
            if (CollUtil.isNotEmpty(dataList)) {
                Map<String, String> tempMap = dataList.stream()
                        .collect(Collectors.toMap(idExtractor, nameExtractor, (o, n) -> n));
                map.putAll(tempMap);
            }
        }
    }

}
